﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.IO;
using System.Net;
using System.Net.Mime;
using System.Data.OleDb;
using System.Text.RegularExpressions;
using System.Collections;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;

namespace EmaillSend
{
    public partial class SendMailForm : Form
    {
        public SendMailForm()
        {
            InitializeComponent();
        }
        SmtpClient SmtpClient = null;   //设置SMTP协议
        MailAddress MailAddress_from = null; //设置发信人地址  当然还需要密码
        FileStream FileStream_my = null; //附件文件流
        bool loadSendMailHead = false;
        //private TreeView mailListMessages;
        private readonly Dictionary<int, Message> messages = new Dictionary<int, Message>();
        private readonly Dictionary<string, Pop3Client> popClients = new Dictionary<string, Pop3Client>();
        private Pop3Client pop3Client;

        #region 设置Ｓmtp服务器信息
        /// <summary>
        /// 设置Ｓmtp服务器信息
        /// </summary>
        /// <param name="ServerName">SMTP服务名</param>
        /// <param name="Port">端口号</param>
        private void setSmtpClient(string ServerHost, int Port)
        {
            SmtpClient = new SmtpClient();
            SmtpClient.Host = ServerHost;//指定SMTP服务名  例如QQ邮箱为 smtp.qq.com 新浪cn邮箱为 smtp.sina.cn等
            SmtpClient.Port = Port; //指定端口号
            SmtpClient.Timeout = 0;  //超时时间
        }
        #endregion
        #region 验证发件人信息
        /// <summary>
        /// 验证发件人信息
        /// </summary>
        /// <param name="MailAddress">发件邮箱地址</param>
        /// <param name="MailPwd">邮箱密码</param>
        private void setAddressform(string MailAddress, string MailPwd)
        {
            //创建服务器认证
            NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd);
            //实例化发件人地址
            MailAddress_from = new System.Net.Mail.MailAddress(MailAddress, Properties.Settings.Default.MailServerShow);
            //指定发件人信息  包括邮箱地址和邮箱密码
            //SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd);
            SmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            SmtpClient.Credentials = NetworkCredential_my;

        }
        #endregion
        #region 检测附件大小
        private bool Attachment_MaiInit(string path)
        {

            try
            {
                FileStream_my = new FileStream(path, FileMode.Open);
                string name = FileStream_my.Name;
                int size = (int)(FileStream_my.Length / 1024 / 1024);
                FileStream_my.Close();
                //控制文件大小不大于10Ｍ
                if (size > 10)
                {

                    MessageBox.Show("文件长度不能大于10M！你选择的文件大小为" + size.ToString() + "M", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                return true;
            }
            catch (IOException E)
            {
                MessageBox.Show(E.Message);
                return false;
            }

        }
        #endregion

        
        #region 发送邮件后所处理的函数
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("发送已取消！");
                }
                else
                {
                    if (e.Error != null)
                    {
                        MessageBox.Show("邮件发送失败！" + "\n" + "技术信息:\n" + e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show("邮件成功发出!", "恭喜!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show("邮件发送失败！" + "\n" + "技术信息:\n" + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadSend();
            this.listMessages.ContextMenu = this.contextMenuMessages;
        }

        private void tabControl1_PaddingChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Equals(this.tabPage3))
            {                
                CommonDBUtils utils = new CommonDBUtils();
                DataSet ds = utils.ReturnDataSet(@"select * from MailGroup");
             
                this.MailGroupDataGridView.DataSource = ds.Tables[0];
            }
            else if (this.tabControl1.SelectedTab.Equals(this.tabPage2))
            {
                CommonDBUtils utils = new CommonDBUtils();
                DataSet ds = utils.ReturnDataSet(@"select * from MailContent");

                this.MailContentComboBox.DataSource = ds.Tables[0];
                this.MailContentComboBox.DisplayMember = "Title";
                this.MailContentComboBox.ValueMember = "ID";
                ChangeTitle();
            }
            else if (this.tabControl1.SelectedTab.Equals(this.tabPage4))
            {
                this.SmptServerName.Text = Properties.Settings.Default.SmtpServerName;
                this.SmtpServerPort.Value = Properties.Settings.Default.SmtpServerPort;
                this.MailServerName.Text = Properties.Settings.Default.MailServerName;
                this.MailServerPwd.Text = Properties.Settings.Default.MailServerPwd;
                this.MailServerShow.Text = Properties.Settings.Default.MailServerShow;
                this.textMailReplay.Text = Properties.Settings.Default.MailReplayAddress;
                this.txtSendMaxMail.Value = Properties.Settings.Default.SendMaxMail;
                this.sendMailTime.Value = Properties.Settings.Default.SendMailTime;
            }
            else if (this.tabControl1.SelectedTab.Equals(this.tabPage6))
            {                
                CommonDBUtils utils = new CommonDBUtils();
                DataSet ds = utils.ReturnDataSet(@"select * from MailSendLog ");
                this.sendLogDataGridView.DataSource = ds.Tables[0];
            }
            else if (this.tabControl1.SelectedTab.Equals(this.tabPage7))
            {
                CommonDBUtils utils = new CommonDBUtils();
                DataSet setServer = utils.ReturnDataSet("select * from MailServer where IsActive=1");

                this.comboBoxServer.DataSource = setServer.Tables[0];
                this.comboBoxServer.DisplayMember = "MailAddress";
                this.comboBoxServer.ValueMember = "ID";
            }
            else if (this.tabControl1.SelectedTab.Equals(this.tabPage8))
            {
                CommonDBUtils utils = new CommonDBUtils();
                DataSet ds = utils.ReturnDataSet(@"select * from VisitEmail order by VisitTime desc ");
                this.visitDataGridView.DataSource = ds.Tables[0];
            }
            else
            {
                LoadSend();
            }
        }

        private void LoadSend()
        {
            CommonDBUtils utils = new CommonDBUtils();
            DataSet ds = utils.ReturnDataSet(@"select * from MailContent");

            this.SendMailTitle.DataSource = ds.Tables[0];
            this.SendMailTitle.DisplayMember = "Title";
            this.SendMailTitle.ValueMember = "ID";

            DataSet ds2 = utils.ReturnDataSet(@"select * from MailGroup");

            this.SendMailMan.DataSource = ds2.Tables[0];
            this.SendMailMan.DisplayMember = "GroupName";
            this.SendMailMan.ValueMember = "ID";
        }



        private void ChangeTitle()
        {
            DataRowView dataRow = (DataRowView)this.MailContentComboBox.SelectedItem;
            if (dataRow != null)
            {
                this.MailTitle.Text = dataRow.Row[2] == null ? "" : dataRow.Row[2].ToString();
                this.MailSubject.Text = dataRow.Row[1] == null ? "" : dataRow.Row[1].ToString();
                this.MailContent.ResetText();
                this.MailContent.BodyHtml = dataRow.Row[3] == DBNull.Value ? "" : System.Text.Encoding.UTF8.GetString((byte[])dataRow.Row[3]);
                this.MailContentID.Text = dataRow.Row[0] == null ? "" : dataRow.Row[0].ToString();
            }
            else
            {
                this.MailContentID.Text = "";
                this.MailTitle.Text = "";
                this.MailSubject.Text = "";
                this.MailContent.ResetText();
            }
            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (this.MailGroupDataGridView.SelectedRows.Count > 0)
            {
                string id = this.MailGroupDataGridView.SelectedRows[0].Cells[0].Value.ToString();
                if (id != null && id != "")
                {                
                    if (DialogResult.OK == MessageBox.Show("确定要删除组吗？删除组后该组的所有邮箱都会删除。"))
                    {
                        CommonDBUtils utils = new CommonDBUtils();                    
                        utils.ExeSQL(@"delete from MailAddress where MailGroup='" + id + "'");
                        utils.ExeSQL(@"delete from MailGroup where ID=" + id );
                    }
                }
                this.MailGroupDataGridView.Rows.RemoveAt(this.MailGroupDataGridView.SelectedRows[0].Index);
            }            
        }

        private void MailGroupDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (this.MailGroupDataGridView.SelectedRows.Count > 0)
            {
                object id = this.MailGroupDataGridView.SelectedRows[0].Cells[0].Value;
                if (id != null && id.ToString() != "")
                {
                    CommonDBUtils utils = new CommonDBUtils();
                    DataSet ds = utils.ReturnDataSet(@"select * from MailAddress where MailGroup='"+id.ToString()+"'");
                    //this.MailAddressDataGridView.Rows.Clear();
                    this.MailAddressDataGridView.DataSource = ds.Tables[0];
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (this.MailAddressDataGridView.SelectedRows.Count > 0)
            {
                CommonDBUtils utils = new CommonDBUtils();
                for (int i = this.MailAddressDataGridView.SelectedRows.Count; i > 0; i--)
                {
                    string id = this.MailAddressDataGridView.SelectedRows[i - 1].Cells["Mail_AddressID"].Value == null ? "" : this.MailAddressDataGridView.SelectedRows[i - 1].Cells["Mail_AddressID"].Value.ToString();
                    if (id != null && id != "")
                    {
                        utils.ExeSQL(@"delete from MailAddress where ID=" + id);
                    }
                    this.MailAddressDataGridView.Rows.RemoveAt(this.MailAddressDataGridView.SelectedRows[i - 1].Index);
                }                
            }   
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (this.MailAddressDataGridView.Rows.Count > 0)
            {
                CommonDBUtils utils = new CommonDBUtils();
                if (this.MailGroupDataGridView.SelectedRows.Count > 0)
                {
                    string id = this.MailGroupDataGridView.SelectedRows[0].Cells[0].Value.ToString();
                    if (id != null && id != "")
                    {
                        utils.ExeSQL(@"delete from MailAddress where MailGroup='" + id + "'");
                    }                   
                }
                DataTable dt = (DataTable)MailAddressDataGridView.DataSource;
                dt.Rows.Clear();
                MailAddressDataGridView.DataSource = dt;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (this.MailGroupDataGridView.Rows.Count > 0)
            {
                CommonDBUtils utils = new CommonDBUtils();
                for (int i = this.MailGroupDataGridView.Rows.Count; i > 0; i--)
                {
                    object id = this.MailGroupDataGridView.Rows[i - 1].Cells["ID"].Value;
                    object name = this.MailGroupDataGridView.Rows[i - 1].Cells["GroupName"].Value;
                    if (name == null)
                    {
                        continue;
                    }
                    if (id != null && id.ToString() != "")
                    {
                        utils.ExeSQL(@"update MailGroup set GroupName='" + name.ToString() + "' where ID=" + id.ToString());
                    }
                    else
                    {
                        utils.ExeSQL(@"insert into MailGroup(GroupName) values('" + name.ToString() + "')");
                    }                    
                }
                DataSet ds = utils.ReturnDataSet(@"select * from MailGroup");

                this.MailGroupDataGridView.DataSource = ds.Tables[0];
            }

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (this.MailAddressDataGridView.Rows.Count > 0)
            {
                CommonDBUtils utils = new CommonDBUtils();
                string groupId = "";
                if (this.MailGroupDataGridView.SelectedRows.Count > 0)
                {
                    groupId = this.MailGroupDataGridView.SelectedRows[0].Cells["ID"].Value == null ? "" : this.MailGroupDataGridView.SelectedRows[0].Cells["ID"].Value.ToString();
                }
                if(groupId == "")
                {
                    MessageBox.Show("没有选择分组");
                    return;
                }
                for (int i = this.MailAddressDataGridView.Rows.Count; i > 0; i--)
                {
                    DataGridViewRow row=this.MailAddressDataGridView.Rows[i - 1];
                    string id = row.Cells["Mail_AddressID"].Value == null ? "" : row.Cells["Mail_AddressID"].Value.ToString();
                    string address = row.Cells["MailAddress"].Value == null ? "" : row.Cells["MailAddress"].Value.ToString();
                    string remark = row.Cells["Remark"].Value == null ? "" : row.Cells["Remark"].Value.ToString();
                    string country = row.Cells["Country"].Value == null ? "" : row.Cells["Country"].Value.ToString();
                    if (address == "")
                    {
                        continue;
                    }
                    if (id != "")
                    {
                        utils.ExeSQL(@"update MailAddress set MailAddress='" + address + "',Remark='" + remark + "',Country='" + country + "' where ID=" + id + "");
                    }
                    else
                    {
                        utils.ExeSQL(@"insert into MailAddress(MailGroup,MailAddress,Remark,Country) values('" + groupId + "','" + address + "','" + remark + "','" + country + "')");
                    }
                }
                DataSet ds = utils.ReturnDataSet(@"select * from MailAddress where MailGroup='" + groupId + "'");

                this.MailAddressDataGridView.DataSource = ds.Tables[0];
            }
        }

        private void MailContentComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeTitle();
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            CommonDBUtils utils = new CommonDBUtils();
            string contentBody=this.MailContent.BodyHtml;
            //MessageBox.Show(contentBody);
            byte[] content = System.Text.Encoding.UTF8.GetBytes(contentBody);
            string images="";
            //正则表达式匹配所有的
            if(this.MailContent.Images.Length > 0){
                for (int i = 0; i < this.MailContent.Images.Length; i++)
                {
                    string tmp = this.MailContent.Images[i];
                    if (tmp.Trim() == "" || !tmp.StartsWith("file"))
                    {
                        continue;
                    }
                    string path = Path.GetFullPath(tmp.Replace("%20", " ").Replace("file:///", ""));
                    string cid = string.Format("image_{0:00}", i);

                    images+=cid+"|~|"+path+"|~~|";
                }
            }
            utils.SaveBinaryData(this.MailTitle.Text, this.MailSubject.Text, content, this.MailContentID.Text,images);
            DataSet ds = utils.ReturnDataSet(@"select * from MailContent");

            this.MailContentComboBox.DataSource = ds.Tables[0];
            MessageBox.Show("保存成功");
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            DataRowView dataRow = (DataRowView)this.MailContentComboBox.SelectedItem;
            if (dataRow != null)
            {
                CommonDBUtils utils = new CommonDBUtils();
                utils.ExeSQL(@"delete from MailContent where ID=" + dataRow.Row[0]);
                dataRow.Delete();
                //ChangeTitle();
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            this.MailContentID.Text = "";
            this.MailTitle.Text = "";
            this.MailSubject.Text = "";
            this.MailContent.BodyHtml = "";
        }


        private MailMessage BuildMessage(string subject,string content,string imgpath)
        {
            MailMessage message = new MailMessage();
            //邮件主题
            message.Subject = subject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;

            List<LinkedResource> list = new List<LinkedResource>();
            //对邮件正文中的图片进行处理
            string[] images=Regex.Split(imgpath,"\\|~~\\|",RegexOptions.IgnoreCase);
            if (images != null && images.Length > 0)
            {
                for(int i=0;i<images.Length;i++){
                    if (images[i] == "")
                        continue;
                    string[] tmp = Regex.Split(images[i], "\\|~\\|", RegexOptions.IgnoreCase);
                    content = content.Replace(tmp[1], string.Format("cid:{0}", tmp[0]));
                    
                    LinkedResource lrImage = new LinkedResource(@tmp[1], MediaTypeNames.Image.Jpeg);   
                    lrImage.ContentId = tmp[0]; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ，如果设置不正确，请不会显示图片
                    list.Add(lrImage);
                }                
            }
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html);
            foreach (LinkedResource item in list)
            {
                htmlBody.LinkedResources.Add(item);
            }
            
            message.Attachments.Clear();
            message.AlternateViews.Clear();
            message.AlternateViews.Add(htmlBody);
            return message;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.MailServerName = this.MailServerName.Text;
            Properties.Settings.Default.MailServerPwd = this.MailServerPwd.Text;
            Properties.Settings.Default.MailServerShow = this.MailServerShow.Text;
            Properties.Settings.Default.SmtpServerName = this.SmptServerName.Text;
            Properties.Settings.Default.SmtpServerPort = this.SmtpServerPort.Value;
            Properties.Settings.Default.MailReplayAddress = this.textMailReplay.Text;
            Properties.Settings.Default.SendMaxMail = this.txtSendMaxMail.Value;
            Properties.Settings.Default.SendMailTime = this.sendMailTime.Value;
            Properties.Settings.Default.Save();
            MessageBox.Show("保存成功！");
        }

        private void bnt_SendControl_Click(object sender, EventArgs e)
        {
            SendMailThread send = new SendMailThread();
            string msg=send.initServer();
            //this.progressBar1.s
            MessageBox.Show(msg);
        }

        private void SendMailMan_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            DataRowView dataRowMan = (DataRowView)this.SendMailMan.SelectedItem;
            if (dataRowMan == null)
            {                
                return;
            }
            CommonDBUtils utils = new CommonDBUtils();
            DataSet ds = utils.ReturnDataSet(@"select * from MailAddress where MailGroup='" + dataRowMan.Row["ID"].ToString() + "'");
            this.SendMailListView.DataSource = ds.Tables[0];
        }

        private void button10_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.CheckPathExists = true;
            this.openFileDialog1.Multiselect = false;

            this.openFileDialog1.ShowDialog();
            this.txtFilePath.Text = this.openFileDialog1.FileName;
        }

        private void button12_Click(object sender, EventArgs e)
        {
            CommonDBUtils dbUtils=new CommonDBUtils();
            if (Utils.isBlank(this.txtFilePath.Text))
            {
                MessageBox.Show("请选择要导入的Excel文件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            try
            {
                DataSet ds = dbUtils.importExcelToDataSet(this.txtFilePath.Text);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string mail = row["邮箱"].ToString();
                    string country = row["国家"].ToString();
                    string remark = row["备注"].ToString();
                    string group = row["分组"].ToString();
                    group = Utils.isBlank(group) ? "1" : group;
                    if (Utils.isNotBlank(mail) && mail.Contains("@"))
                    {
                        dbUtils.ExeSQL(@"insert into MailAddress(MailGroup,MailAddress,Remark,Country) values('" + group + "','" + mail.Trim() + "','" + remark + "','" + country + "')");
                    }
                }
                MessageBox.Show("导入成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

        private void button13_Click(object sender, EventArgs e)
        {
            DataRowView dataRow = (DataRowView)this.SendMailTitle.SelectedItem;
            if (dataRow == null)
            {
                MessageBox.Show("请选择要发送的邮件模版！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string contentid = dataRow.Row[0].ToString();
         
            DataTable table = (DataTable)this.SendMailListView.DataSource;
            if (table.Rows.Count > 0)
            {
                List<string> sql = new List<string>();
                foreach (DataRow row in table.Rows)
                {
                    string mail = row["MailAddress"] == null ? "" : row["MailAddress"].ToString();
                    if (mail == null || mail == "")
                        continue;
                    sql.Add("insert into MailSendLog(Mail,ContentID,IsSend) values('"+mail+"','"+contentid+"','0')");
                }
                CommonDBUtils utils = new CommonDBUtils();
                utils.ExeBatchSQL(sql);

                string delSql = "delete * from MailSendLog where id not in(select min(id) from MailSendLog group by Mail,ContentID,IsSend)";
                utils.ExeSQL(delSql);               
            }

        }

        private void sendLogDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in this.sendLogDataGridView.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void MailAddressDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in this.MailAddressDataGridView.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            DataRowView dataRow = (DataRowView)this.comboBoxServer.SelectedItem;
            if (dataRow != null)
            {
                listMessages.Nodes.Clear();

                string servername = dataRow.Row[9].ToString();
                int port = (int)dataRow.Row[10];
                string mailaddress = dataRow.Row[3].ToString();
                string account = dataRow.Row[4].ToString();
                string password = dataRow.Row[5].ToString();
                int type = (int)dataRow.Row[11];
                bool ssl = type == 1 ? true:false;
                loadMessage(servername, port, account, password, mailaddress, ssl);               
            }            
                      
        }

        private void loadMessage(string server, int port, string username, string password, string address, bool ssl)
        {
            this.btnBack.Enabled = false;
            this.button14.Enabled = false;
            if(pop3Client != null){
                if (pop3Client.Connected)
                    pop3Client.Disconnect();                
            }
            pop3Client = new Pop3Client();
            try
            {
                pop3Client.Connect(server, port, ssl);
                pop3Client.Authenticate(username, password);
                int count = pop3Client.GetMessageCount();
                LogHelper.InfoLog("");
                int success = 0;
                int fail = 0;
                this.listMessages.Nodes.Clear();
                this.messages.Clear();
                for (int i = count; i >= 1; i -= 1)
                {
                    // Check if the form is closed while we are working. If so, abort
                    if (IsDisposed)
                        return;

                    // Refresh the form while fetching emails
                    // This will fix the "Application is not responding" problem
                    Application.DoEvents();
                    try
                    {
                        Message message = pop3Client.GetMessage(i);

                        // Add the message to the dictionary from the messageNumber to the Message
                        messages.Add(i, message);

                        // Create a TreeNode tree that mimics the Message hierarchy
                        TreeNode node = new TreeNodeBuilder().VisitMessage(message);

                        // Set the Tag property to the messageNumber
                        // We can use this to find the Message again later
                        node.Tag = i;

                        // Show the built node in our list of messages
                        listMessages.Nodes.Add(node);

                        success++;
                    }
                    catch (Exception e)
                    {
                        DefaultLogger.Log.LogError(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                        fail++;
                    }                   
                }

                //MessageBox.Show(this, "Server:"+address+" Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done");
                this.showmsgtext.Text = "Server:" + address + " received! Successes: " + success + " Failed: " + fail;
                if (fail > 0)
                {
                    MessageBox.Show(this,
                                    "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                    "please consider sending your log file to the developer for fixing.\r\n" +
                                    "If you are able to include any extra information, please do so.",
                                    "Help improve OpenPop!");
                }
            }
            catch (InvalidLoginException)
            {
                MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
            }
            catch (PopServerNotFoundException)
            {
                MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
            }
            catch (PopServerLockedException)
            {
                MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
            }
            catch (LoginDelayException)
            {
                MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
            }
            finally
            {
                //if (pop3Client.Connected)
                //    pop3Client.Disconnect();
                //if (!popClients.ContainsKey(address))
                //    popClients.Add(address, pop3Client);
                this.btnBack.Enabled = true;
                this.button14.Enabled = true;
            }
        }

        private void listMessages_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // Fetch out the selected message
            Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)];

            // If the selected node contains a MessagePart and we can display the contents - display them
            if (listMessages.SelectedNode.Tag is MessagePart)
            {
                MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag;
                if (selectedMessagePart.IsText)
                {
                    // We can show text MessageParts
                    messageTextBox.BodyHtml = selectedMessagePart.GetBodyAsText();
                }
                else
                {
                    // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...)
                    messageTextBox.BodyHtml = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>";
                }
            }
            else
            {
                // If the selected node is not a subnode and therefore does not
                // have a MessagePart in it's Tag property, we genericly find some content to show

                // Find the first text/plain version
                MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                if (plainTextPart != null)
                {
                    // The message had a text/plain version - show that one
                    messageTextBox.BodyHtml = plainTextPart.GetBodyAsText();
                }
                else
                {
                    // Try to find a body to show in some of the other text versions
                    List<MessagePart> textVersions = message.FindAllTextVersions();
                    if (textVersions.Count >= 1)
                        messageTextBox.BodyHtml = textVersions[0].GetBodyAsText();
                    else
                        messageTextBox.BodyHtml = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                }
            }

            
            // Generate header table
            DataSet dataSet = new DataSet();
            DataTable table = dataSet.Tables.Add("Headers");
            table.Columns.Add("Header");
            table.Columns.Add("Value");
            

            DataRowCollection rows = table.Rows;

            // Add all known headers
            rows.Add(new object[] { "Content-Description", message.Headers.ContentDescription });
            rows.Add(new object[] { "Content-Id", message.Headers.ContentId });
            foreach (string keyword in message.Headers.Keywords) rows.Add(new object[] { "Keyword", keyword });
            foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) rows.Add(new object[] { "Disposition-Notification-To", dispositionNotificationTo });
            foreach (Received received in message.Headers.Received) rows.Add(new object[] { "Received", received.Raw });
            rows.Add(new object[] { "Importance", message.Headers.Importance });
            rows.Add(new object[] { "Content-Transfer-Encoding", message.Headers.ContentTransferEncoding });
            foreach (RfcMailAddress cc in message.Headers.Cc) rows.Add(new object[] { "Cc", cc });
            foreach (RfcMailAddress bcc in message.Headers.Bcc) rows.Add(new object[] { "Bcc", bcc });
            foreach (RfcMailAddress to in message.Headers.To) rows.Add(new object[] { "To", to });
            rows.Add(new object[] { "From", message.Headers.From });
            rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo });
            foreach (string inReplyTo in message.Headers.InReplyTo) rows.Add(new object[] { "In-Reply-To", inReplyTo });
            foreach (string reference in message.Headers.References) rows.Add(new object[] { "References", reference });
            rows.Add(new object[] { "Sender", message.Headers.Sender });
            rows.Add(new object[] { "Content-Type", message.Headers.ContentType });
            rows.Add(new object[] { "Content-Disposition", message.Headers.ContentDisposition });
            rows.Add(new object[] { "Date", message.Headers.Date });
            rows.Add(new object[] { "Date", message.Headers.DateSent });
            rows.Add(new object[] { "Message-Id", message.Headers.MessageId });
            rows.Add(new object[] { "Mime-Version", message.Headers.MimeVersion });
            rows.Add(new object[] { "Return-Path", message.Headers.ReturnPath });
            rows.Add(new object[] { "Subject", message.Headers.Subject });

            // Add all unknown headers
            foreach (string key in message.Headers.UnknownHeaders)
            {
                string[] values = message.Headers.UnknownHeaders.GetValues(key);
                if (values != null)
                    foreach (string value in values)
                    {
                        rows.Add(new object[] { key, value });
                    }
            }

            // Now set the headers displayed on the GUI to the header table we just generated
            gridHeaders.DataMember = table.TableName;
            gridHeaders.DataSource = dataSet;
        }

        /// <summary>
        /// Finds the MessageNumber of a Message given a <see cref="TreeNode"/> to search in.
        /// The root of this <see cref="TreeNode"/> should have the Tag property set to a int, which
        /// points into the <see cref="messages"/> dictionary.
        /// </summary>
        /// <param name="node">The <see cref="TreeNode"/> to look in. Cannot be <see langword="null"/>.</param>
        /// <returns>The found int</returns>
        private static int GetMessageNumberFromSelectedNode(TreeNode node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            // Check if we are at the root, by seeing if it has the Tag property set to an int
            if (node.Tag is int)
            {
                return (int)node.Tag;
            }

            // Otherwise we are not at the root, move up the tree
            return GetMessageNumberFromSelectedNode(node.Parent);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            DialogResult drRet = MessageBox.Show(this, "Are you sure to delete the all email(count "+messages.Count.ToString()+")?", "Delete email", MessageBoxButtons.YesNo);
            if (drRet == DialogResult.Yes)
            {
                int num = 0;
                Message message;
                this.btnBack.Enabled = false;
                this.button14.Enabled = false;
                try
                {
                    CommonDBUtils utils = new CommonDBUtils();
                    List<string> sqls = new List<string>();
                    foreach (TreeNode node in this.listMessages.Nodes)
                    {
                        num = GetMessageNumberFromSelectedNode(node);
                        message = messages[num];
                        if (message == null)
                            continue;
                        //取得退信的地址
                        string backemail = "";
                        string to = message.Headers.To[0].ToString();
                        if (to.Contains("@gmail.com"))
                        {
                            string[] values = message.Headers.UnknownHeaders.GetValues("X-Failed-Recipients");
                            if (values != null)
                            {
                                backemail = values[0];
                            }
                        }
                        else if (to.Contains("@ledsou.com"))
                        {
                            //MessageBox.Show(message.ToMailMessage().Body);
                            Regex gex = new Regex(@"无法发送到(.*)</td>");                            
                            // Find the first text/plain version
                            string msgtext = "";
                            MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                            if (plainTextPart != null)
                            {
                                msgtext = plainTextPart.GetBodyAsText();
                            }
                            else
                            {
                                List<MessagePart> textVersions = message.FindAllTextVersions();
                                if (textVersions.Count >= 1)
                                    msgtext = textVersions[0].GetBodyAsText();                                
                            }
                            //MessageBox.Show(msgtext);
                            backemail = gex.Match(message.ToMailMessage().Body).Groups[1].Value;
                            //MessageBox.Show(backemail);
                        }
                        else
                        {
                            string[] values = message.Headers.UnknownHeaders.GetValues("Delivered-To");
                            if (values != null)
                            {
                                backemail = values[0];
                            }
                        }

                        if (Utils.isNotBlank(backemail))
                        {
                            pop3Client.DeleteMessage(num);
                            //MessageBox.Show(values[0]);
                            sqls.Add("delete * from MailAddress where MailAddress = '" + backemail + "'");
                        }


                    }
                    utils.ExeBatchSQL(sqls);
                    this.listMessages.Nodes.Clear();
                    this.listMessages.Refresh();
                    this.showmsgtext.Text = "处理完成";
                }
                catch (Exception ex)
                {
                    this.showmsgtext.Text = ex.Message;
                }
                finally
                {
                    this.btnBack.Enabled = true;
                    this.button14.Enabled = true;
                }
                //MessageBox.Show("处理完成");
                
                
            }
        }

        private void menuDeleteMessage_Click(object sender, EventArgs e)
        {
            if (listMessages.SelectedNode != null)
            {
                //DialogResult drRet = MessageBox.Show(this, "Are you sure to delete the email?", "Delete email", MessageBoxButtons.YesNo);
                //if (drRet == DialogResult.Yes)
                //{
                    int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
                    listMessages.Nodes.Remove(listMessages.SelectedNode);
                    listMessages.Refresh();
                    messages.Remove(messageNumber);
                //}
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            /*MailMessage message = new MailMessage();
            message.From = new MailAddress("sandy106525@gmail.com", "Your DisplayName");
            message.To.Add(new MailAddress("106709483@qq.com")); // the email you want to send email to
            message.Subject = "A test email";

            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Body = "this is just a simple test!<br> Jack";
            message.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587); // 587;//Gmail使用的端口
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential("sandy106525@gmail.com", "satellite"); // Your user name & password
            client.EnableSsl = true; //经过ssl加密 
            object userState = message; 
            try
            {
            client.Send(message);
            //Response.Write("邮件发送到" + message.To.ToString() + "<br>");
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
           // Response.Write(ee.messageage + "<br>" + ee.InnerException.messageage);
            }*/
            //string email = "sandy106525@163.com";
            //string code = Utils.Basic64Ecode(email);
            //MessageBox.Show(code);
            //MessageBox.Show(Utils.Basic64Dcode(code));
           
        }

        private void button16_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.CheckPathExists = true;
            this.openFileDialog1.Multiselect = false;

            this.openFileDialog1.ShowDialog();
            this.txtVisitSource.Text = this.openFileDialog1.FileName;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            CommonDBUtils dbUtils = new CommonDBUtils();
            if (Utils.isBlank(this.txtVisitSource.Text))
            {
                MessageBox.Show("请选择要导入的Excel文件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            try
            {
                DataSet ds = dbUtils.importExcelToDataSet(this.txtVisitSource.Text);
                List<string> sqls = new List<string>();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string mail = row["Email"].ToString();
                    string time = row["Time"].ToString();
                    if (Utils.isNotBlank(mail))
                    {
                        mail = Utils.Basic64Dcode(mail);
                        if (dbUtils.ReturnSqlResultCount(@"select * from VisitEmail where Email='" + mail.Trim() + "'") > 0)
                        {
                            dbUtils.ExeSQL(@"update VisitEmail set VisitTime = '" + time + "',VisitCount = VisitCount+1 where Email='" + mail.Trim() + "'");
                        }
                        else
                        {
                            dbUtils.ExeSQL(@"insert into VisitEmail(Email,VisitTime,VisitCount) values('" + mail.Trim() + "','" + time + "',1)"); 
                        }
                        
                    }
                }
                //dbUtils.ExeBatchSQL(sqls);
                DataSet ds2 = dbUtils.ReturnDataSet(@"select * from VisitEmail order by VisitTime desc ");
                this.visitDataGridView.DataSource = ds2.Tables[0];
                MessageBox.Show("导入成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void visitDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in this.visitDataGridView.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void button15_Click_1(object sender, EventArgs e)
        {
            string mail=this.textDeleteMail.Text.Trim();
            if (Utils.isNotBlank(mail))
            {
                CommonDBUtils utils = new CommonDBUtils();
                utils.ExeSQL(@"delete * from MailAddress where MailAddress='" + mail + "'");
            }        

        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            if (listMessages.SelectedNode != null)
            {
                DialogResult drRet = MessageBox.Show(this, "Are you sure to delete the email?", "Delete email", MessageBoxButtons.YesNo);
                if (drRet == DialogResult.Yes)
                {
                    int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
                    listMessages.Nodes.Remove(listMessages.SelectedNode);
                    listMessages.Refresh();
                    messages.Remove(messageNumber);
                    pop3Client.DeleteMessage(messageNumber);
                }
            }
        }
    }
}
